package com.neusoft.databus.policy.event.impl;

import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.utils.SpringUtil;
import com.neusoft.databus.policy.bean.EventBean;
import com.neusoft.databus.policy.enums.PolicyType;
import com.neusoft.databus.policy.event.PolicyEventHandler;
import com.neusoft.databus.policy.event.PolicyEventParser;
import com.neusoft.databus.policy.model.Policy;

import lombok.extern.slf4j.Slf4j;

/**
 * 事件解析器
 *
 * @author naxiang
 */
@Slf4j
@Component
public class PolicyEventParserImpl implements PolicyEventParser {
    // 注入Handler,根据不同的Handler调用不同的
    private PolicyEventHandler policyEventHandler;

    @Override
    public void receiveEvents(final EventBean eventBean) {
        for (final Policy policy : eventBean.getPolicies()) {
            final PolicyType type = policy.getPolicyType();
            switch (type) {
            case SYSTEM:
                // 系统异常事件
                this.policyEventHandler = (PolicyEventHandler) SpringUtil.getBean("sysTemEventHandler");
                break;
            case DEVICE_FAULT:
                // 设备故障事件
                this.policyEventHandler = (PolicyEventHandler) SpringUtil.getBean("faultPolicyEventHandler");
                break;
            case GATEWAY_DISCONNECT:
                // 通讯中断事件
                this.policyEventHandler = (PolicyEventHandler) SpringUtil.getBean("suspendPolicyEventHandler");
                break;
            case POLICY_ALARM:
                // 策略事件
                this.policyEventHandler = (PolicyEventHandler) SpringUtil.getBean("policyEventHandler");
                break;
            case POLICY_COMPLEX:
                // 复杂策略事件
                this.policyEventHandler = (PolicyEventHandler) SpringUtil.getBean("policyEventHandler");
                break;
            default:
                PolicyEventParserImpl.log.error("缺少Event类型为{}的Event信息的处理类，请确认数据", type);
                return;
            }
            if (eventBean.getExpressionResult()) {
                this.policyEventHandler.trigger(eventBean.getResourceBean(), eventBean.getTime(), policy,
                        eventBean.getExpressionTrueSquence());
                PolicyEventParserImpl.log.info("告警事件,告警类型:{},资源code:{}，策略code:{}", type,
                        eventBean.getResourceBean().getCode(), policy.getCode());
            } else {
                this.policyEventHandler.fixed(eventBean.getResourceBean(), eventBean.getTime(), policy);
                //                PolicyEventParserImpl.log.info("解除告警事件,告警类型:{},资源code:{}", type,
                //                        eventBean.getResourceBean().getCode());
            }
        }
    }
}
